package cn.amebius.thread;

import cn.amebius.util.DockerClientUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.AttachContainerCmd;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.AttachContainerResultCallback;
import com.github.dockerjava.netty.NettyDockerCmdExecFactory;
import com.github.dockerjava.core.DockerClientConfig;

import java.io.InputStream;
import java.util.Scanner;

/**
 * @author 阿伟
 * @date 2023/7/24 19:15
 */
public class AttachConsoleThread extends Thread {
    @Override
    public void run() {
        DefaultDockerClientConfig ddcc = DefaultDockerClientConfig.createDefaultConfigBuilder().withDockerHost("tcp://192.168.121.140:2376").build();
        NettyDockerCmdExecFactory nettyDockerCmdExecFactory =  new NettyDockerCmdExecFactory();
        DockerClient dc = DockerClientBuilder.getInstance(ddcc).withDockerCmdExecFactory(nettyDockerCmdExecFactory).build();
        AttachContainerCmd acc = dc.attachContainerCmd(DockerClientUtil.getContainerId());
        InputStream is = System.in;
        try {
            acc.withStdOut(true)
                    .withStdErr(true)
                    .withFollowStream(true)
                    .withStdIn(is)
                    .withLogs(true)
                    .exec(new AttachContainerResultCallback() {
                        @Override
                        public void onError(Throwable throwable) {
                            throwable.printStackTrace();
                            System.out.println(throwable.getMessage());
                        }
                        @Override
                        public void onNext(Frame item) {
                            System.out.println("【Log日志】 "+ new String(item.getPayload()));
                        }
                    });
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException(e);
        }
    }
    //Passing stdin to the container is currently not supported. Try experimental netty engine!
}
